package com.macrosolution.exdebito.utility

import org.codehaus.groovy.grails.plugins.web.taglib.JavascriptTagLib;

import com.macrosolution.exdebito.User;

class UtilityTagLib extends JavascriptTagLib {
	
	static namespace = "exdutility"
	def springSecurityService
	
	def sec_personal_email={
		String pEmail
		User user
		if(springSecurityService){
			//se la tag library e richiamata in una pagina di errori (404,500),
			 //non ha la sessione per fare le query
			try{
			 user= springSecurityService.currentUser
			}catch(Exception ex){
			out << pEmail
			return
			}
			if(user){
				pEmail=user.personal_email
			}
		}
		out << pEmail
	} 
	
	def number_interview = {attrs ->
		def value = ''+attrs.get('value')
		int sizeValue = value.length()
		String app=''
		for(int i =6;sizeValue<=i;i--){
			app +='0'
		}
		value=app+value
		out << value
	}
	
	def double_number = {attrs ->
		def value = ''+attrs.get('value')
		int sizeValue = value.length()
		String app=''
		for(int i =1;sizeValue<=i;i--){
			app +='0'
		}
		value=app+value
		out << value
	}
	
	def btn_manage = { attrs ->
		User secUser =springSecurityService.currentUser
		boolean isReadOnly = secUser.isReadOnly()
		String result=''
		if(isReadOnly){
			result='<span><a href="'+createLink(controller:''+attrs.get('controller')+'',action:''+attrs.get('action')+'',id:attrs.get('id'))+'" ><i class="fa fa-lg fa-eye"></i></a> </span>'
		}else{
			result='<span><a href="'+createLink(controller:''+attrs.get('controller')+'',action:''+attrs.get('action')+'',id:attrs.get('id'))+'" ><i class="fa fa-lg fa-edit"></i></a> </span>&nbsp;&nbsp;&nbsp;<span><a href="#" onclick="'+attrs.get('cancel-function')+'"><i class="fa fa-lg fa-trash-o"></i></a> </span>'
		}
		out <<result
	}
	
	def btn_manage1 = { attrs ->
		User secUser =springSecurityService.currentUser
		boolean isReadOnly = secUser.isReadOnly()
		String result=''
		if(isReadOnly){
			result='<span><a href="#" ><i class="fa fa-lg fa-eye"></i></a> </span>'
		}else{
			result='<span><a href="#" onclick="'+attrs.get('cancel-function')+'"><i class="fa fa-lg fa-trash-o"></i></a> </span>'
		}
		out <<result
	}
	
	def isReadOnly = { attrs,body ->
				User secUser =springSecurityService.currentUser
				if(attrs.get('test')=='true'){
					if(secUser.isReadOnly()){
						out << body()
					}
				}else if(attrs.get('test')=='false'){
					if(!secUser.isReadOnly()){
						out << body()
					}
				}		
		}
	
	def truncateText ={ attr->
		
		String stringIn = attr.get('stringIn')
		def maxSize = attr.getInt('max-size')
		def strLenght = stringIn.length()
		if(strLenght>maxSize){
			
			String ot = stringIn.substring(0, maxSize - 3)
			ot = ot.concat("...")
			out << ot
			
		}else{
		
			out << stringIn
		}
		
		
		
	}
}
